import types from '@/store/mutations/mutation-types';
import dao from '@/dao';
import Storage from '@/lib/storage';
// import ResonpseHandler, { commitGlobalMessage } from './response-handler';
import ResonpseHandler2 from './response-handler2';
import ResonpseHandler, { commitGlobalMessage } from './response-handler';
import PREFIX from '@/router/prefix.js';
const Cookies = new Storage('cookie');


G_useCodeHandlers(ResonpseHandler2);

/*
 * 清除系统下所有的cookie
 */
const clearCookie = function () {
   Cookies.removeItem();
};

/**
 * 检测portalName是否存在
 */
const checkPortalName = function (payload) {
    if (!payload.name) {
        throw new Error('proxyAction needs portal name!');
    }
};


const actions = {
    loading({ commit }, value) {
        commit(types.LOADING, value !== undefined ? value : true);
    },

     /**
     * 跳转到用户权限范围内的第一个可用菜单
     */
    goHome({ commit, dispatch, state }, payload) {
        let homeRoute = state.user?.userPermission?.homeRoute || {};
        window.location.href = homeRoute?.route?.path || `${PREFIX}/welcome`
    },

    /**
     * 退出 + 跳转到登录页
     */
    logout({ commit, dispatch, state }, payload = true) {
        if(window.location.pathname === `${PREFIX}/login`) {
			return;
		}
        let loginUrl = `${PREFIX}/login?authUrl=`;
        clearCookie();
        let authUrl = payload ? encodeURIComponent(window.location.href) : '';
        window.location.href = loginUrl + authUrl;
    },
    /**
	 * 设置cookie
	 * @param {Object}  payload 
	 * payload 实例：
	 * {
	 *	 data: {'X-DT-accessToken': 'xx'},
	 *   params: { expires: 30 }
	 * }
	 * @param {Boolean}  isClearCookie 设置cookie前是否要先清除所有的cookie
	 */
	setCookie({commit, dispatch, state}, payload, isClearCookie) {
		if(isClearCookie) {
			clearCookie();
		}
		if(payload) {
            // Cookies.setItem(key, data[key], params);
			let { data, params } = payload;
			for(let key in data) {
				Cookies.setItem(key, {value: data[key], params: params});
			}
		}
	},

    /**
     * 设置state数据
     * @param {Object}  payload {
     * 	 state属性Key: value
     * }
     */
    meta({ commit, dispatch, state }, payload) {
        commit(types.META, payload);
    },

    /**
     * 消息提示，所有的toast提示都走message，不要单独调用组件的message
     * @param {Object} payload {
     *	 msg: toast的文本内容,
     *   type: 'success' || 'loading' || 'none'   默认为 'none'
     * 	 duration: 3000 默认为3秒
     * }
     */
    message({ commit, dispatch, state }, payload) {
        commit(types.MESSAGE, payload);
    },

    /**
     * 埋点代理, 所有的埋点采用action的方式，放弃分散引用模式
     * @param {Object} payload {
     *	 name: string name(必须), 事件名
     * 	 data: object 需要追踪的数据
     * }
     */
    proxyTrack({ commit, dispatch, state }, payload) {
        // RecordData.track(payload.name, payload.data);
    },

    /**
     * 接口代理，没有特殊情况的接口都通过此方法进行代码，可覆盖大部分操作
     *
     * @param {Object} info => {
     *    name: action name(必须), 即 porter/portals.js 里的配置名称
     *    txtSuccess: 成功消息。true/字符串 显示；false/不传 不显示；
     *    txtError: 失败消息。true/字符串/不传 显示；false 不显示；
     *    queries: 请求参数 (url 问号后面的参数)
     *    data: form data 数据
     *    params: 替换portals 里的 uri 里的参数的内容
     *    uri: 替换portals里定义的 uri
     *    headers: 与 portals里定义的 headers 合并
     * }
     */
    proxyAction({ commit, dispatch, state }, payload) {
        checkPortalName(payload);
        // 只有状态码为200的时候才会走resolve, 其他都走reject
        return new Promise((resolve, reject) => {
            dao.x(payload).then((res) => {
				let { status } = res;
                let { code } = status;
				let handler = ResonpseHandler[code];
				if (handler) {
					handler(commit, dispatch, state, res, payload);
				}
				// commitGlobalMessage(commit, res, payload);
				// 状态码为 200 时走resolve, 其他情况都走reject
				if(code == 200) {
					resolve(res);
				} else {
                    commitGlobalMessage(commit, res, payload);
					reject(res);
				}
			})
			.catch((err) => {
				commitGlobalMessage(commit, {
                    status: {
                        code: -1,
                        desc: err.message
                    }
				}, payload);
				reject(err);
			});
        });
    }
};

export default actions;
